﻿using CDV.IRMS.Model;
using CDV.IRMS.WebAPI.TaskExecution.Data;
using CDV.IRMS.WebAPI.TaskExecution.Utils;
using log4net;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;

namespace CDV.IRMS.WebAPI.TaskExecution.Interface.Impl
{
    /// <summary>
    /// 资源管理服务实现类
    /// </summary>
    public class ResourceManagerServiceImpl : IResourceManagerService
    {
        /// <summary>
        /// Log对象
        /// </summary>
        private readonly ILog _logger = ServiceInjector.ServiceProvider.GetService<ILog>();

        /// <summary>
        /// 矩阵控制接口API
        /// </summary>
        public RESTfulAPI RESTfulAPI { get; set; }

        /// <summary>
        /// 校验节点占用状态
        /// </summary>
        /// <param name="taskID">任务ID</param>
        /// <param name="routeID">路由ID</param>
        /// <param name="srcNodeID">源节点ID</param>
        /// <param name="destNodeID">目的节点ID</param>
        /// <returns>(占用状态，错误信息)</returns>
        public (bool, string) HasNodeConflict(int taskID, int routeID, string srcNodeID, string destNodeID)
        {
            using (var httpClient = new HttpClient())
            {
                httpClient.BaseAddress = new Uri(RESTfulAPI.BaseURL);
                httpClient.Timeout = RESTfulAPI.TimeOut;

                var requestUri = string.Format(RESTfulAPI.APIMap["CheckNodeConflict"], taskID, routeID, srcNodeID, destNodeID);

                var response = httpClient.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead);
                if (response.Result.StatusCode == HttpStatusCode.OK)
                {
                    var jsonResult = response.Result.Content.ReadAsStringAsync();

                    var result = JsonConvert.DeserializeAnonymousType(jsonResult.Result,
                        new { IsOK = false, Msg = "", Data = new Dictionary<string, TaskRouteInfoModel>() });

                    _logger.Debug($"RequestUri: {requestUri}, Result: [IsOK={result.IsOK}, Msg={result.Msg}]");

                    if (!result.IsOK)
                    {
                        return (false, result.Msg);
                    }

                    //没有节点冲突信息
                    if (result.Data == null || result.Data.Count == 0)
                    {
                        return (false, string.Empty);
                    }

                    var conflictMsg = new StringBuilder("路由节点存在冲突信息：");

                    foreach (var item in result.Data)
                    {
                        if (item.Value == null)
                        {
                            continue;
                        }
                        var routeNode = item.Value.TaskRouteNodes?.SingleOrDefault(node => node.NodeID == item.Key);
                        conflictMsg.AppendLine().Append($"    资源节点[{(routeNode == null ? item.Key : routeNode.NodeName)}]被任务[{item.Value.Task?.TaskName}(任务ID={item.Value.TaskId},路由ID={item.Value.Id})]占用中");
                    }
                    return (true, conflictMsg.ToString());
                }

                return (true, $"资源节点占用情况检测失败，原因-[{response.Result.StatusCode}]");
            }
        }
    }
}
